package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.common.core.constant.enums.DictNameEnum;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.data.web.query.Pages;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.data.web.response.PageInfo;
import com.engine4cloud.tdf.common.data.web.response.Params;
import com.engine4cloud.tdf.supervision.convert.JzdxResumeConvert;
import com.engine4cloud.tdf.supervision.dto.create.JzdxResumeCreateDTO;
import com.engine4cloud.tdf.supervision.dto.query.JzdxResumeQueryDTO;
import com.engine4cloud.tdf.supervision.dto.result.DictSelectResultDTO;
import com.engine4cloud.tdf.supervision.dto.result.JzdxResultDTO;
import com.engine4cloud.tdf.supervision.dto.result.JzdxResumeResultDTO;
import com.engine4cloud.tdf.supervision.dto.update.JzdxResumeUpdateDTO;
import com.engine4cloud.tdf.supervision.entity.JzdxResumeEntity;
import com.engine4cloud.tdf.supervision.mapper.JzdxResumeMapper;
import com.engine4cloud.tdf.supervision.service.DictSelectService;
import com.engine4cloud.tdf.supervision.service.JzdxResumeService;
import com.engine4cloud.tdf.supervision.service.JzdxService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 矫正对象个人履历信息表
 *
 * @author wenjie
 * @date 2024-04-01 14:21:08
 */
@Service
public class JzdxResumeServiceImpl extends ServiceImpl<JzdxResumeMapper, JzdxResumeEntity> implements JzdxResumeService {
    @Resource
    private JzdxService jzdxService;

    @Resource
    private DictSelectService dictSelectService;

    @Override
    public PageInfo<JzdxResumeResultDTO> pageList(Params pageable, JzdxResumeQueryDTO dto) {
        IPage<JzdxResumeResultDTO> page = this.baseMapper.pageList(Pages.page(pageable), dto);
        return Pages.convert(page);
    }

    @Override
    public List<JzdxResumeResultDTO> findList(JzdxResumeQueryDTO dto) {
        return list(wrapper(dto)).stream().map(JzdxResumeConvert.INSTANCE::convert).toList();
    }

    @Override
    public Boolean create(JzdxResumeCreateDTO dto) {
        JzdxResultDTO dx = Optional.ofNullable(jzdxService.getByCode(dto.getRybh()))
                .orElseThrow(() -> new ValidateCodeException("矫正对象数据不存在"));

        return super.save(JzdxResumeConvert.INSTANCE.create(dto, dx.getTenantId()));
    }

    @Override
    public Boolean update(JzdxResumeUpdateDTO dto) {
        JzdxResumeEntity old = Optional.ofNullable(super.getById(dto.getId()))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));
        return super.updateById(JzdxResumeConvert.INSTANCE.update(dto));
    }

    @Override
    public JzdxResumeResultDTO getById(Long id) {
        //设置职务
        List<DictSelectResultDTO> jobList = dictSelectService.items(DictNameEnum.JOB.getType());
        return JzdxResumeConvert.INSTANCE.convert(super.getById(id), jobList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createBatch(String code, List<JzdxResumeEntity> resumeEntityList) {
        JzdxResultDTO dx = Optional.ofNullable(jzdxService.getByCode(code))
                .orElseThrow(() -> new ValidateCodeException("矫正对象数据不存在"));

        if (CollectionUtils.isNotEmpty(resumeEntityList)) {
            resumeEntityList.forEach(each -> each.setRybh(code));
            super.saveBatch(resumeEntityList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateBatch(String code, List<JzdxResumeEntity> resumeEntityList) {
        //查询已经存在的
        List<JzdxResumeResultDTO> existedList = this.findList(new JzdxResumeQueryDTO(code));

        //需要保存的
        List<JzdxResumeEntity> preSaveList = this.preSaveList(resumeEntityList);
        if (CollectionUtils.isNotEmpty(preSaveList)) {
            this.saveBatch(preSaveList);
        }

        //需要删除的
        List<Long> preDeleteList = this.preDeleteList(existedList, resumeEntityList);
        if (CollectionUtils.isNotEmpty(preDeleteList)) {
            this.removeBatchByIds(preDeleteList);
        }

        //需要更新的
        List<JzdxResumeEntity> preUpdateList = this.preUpdateList(existedList, resumeEntityList);
        if (CollectionUtils.isNotEmpty(preUpdateList)) {
            this.updateBatchById(preUpdateList);
        }

        return true;
    }

    @Override
    public List<JzdxResumeEntity> findByCode(String code) {
        LambdaQueryWrapper<JzdxResumeEntity> wrapper = Queries.lambda();
        Queries.accept(code, v -> wrapper.eq(JzdxResumeEntity::getRybh, v));
        return list(wrapper);
    }

    private LambdaQueryWrapper<JzdxResumeEntity> wrapper(JzdxResumeQueryDTO query) {
        LambdaQueryWrapper<JzdxResumeEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(JzdxResumeEntity::getId, v));
        Queries.accept(query.getRybh(), v -> wrapper.eq(JzdxResumeEntity::getRybh, v));
        return wrapper;
    }

    private List<JzdxResumeEntity> preSaveList(List<JzdxResumeEntity> entityList) {
        if (CollectionUtils.isEmpty(entityList)) {
            return Collections.emptyList();
        }

        return entityList.stream().filter(file -> Objects.isNull(file.getId())).toList();
    }

    private List<Long> preDeleteList(List<JzdxResumeResultDTO> existedList, List<JzdxResumeEntity> modelList) {
        if (CollectionUtils.isEmpty(existedList)) {
            return Collections.emptyList();
        }

        Map<Long, JzdxResumeEntity> modelMap = modelList.stream().filter(model -> Objects.nonNull(model.getId())).collect(Collectors.toMap(JzdxResumeEntity::getId, Function.identity(), (v1, v2) -> v1));
        return existedList.stream().map(JzdxResumeResultDTO::getId).filter(id -> !modelMap.containsKey(id)).toList();
    }

    private List<JzdxResumeEntity> preUpdateList(List<JzdxResumeResultDTO> existedList, List<JzdxResumeEntity> modelList) {
        if (CollectionUtils.isEmpty(existedList) || CollectionUtils.isEmpty(modelList)) {
            return Collections.emptyList();
        }

        List<JzdxResumeEntity> preUpdateList = new ArrayList<>();

        Map<Long, JzdxResumeResultDTO> existedMap = existedList.stream().collect(Collectors.toMap(JzdxResumeResultDTO::getId, v -> v));
        for (JzdxResumeEntity resume : modelList) {
            if (Objects.nonNull(resume.getId()) && existedMap.containsKey(resume.getId())) {
                preUpdateList.add(resume);
            }
        }

        return preUpdateList;
    }

}